package dnl.confij;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import dnl.confij.ini.IniConfiguration;
import dnl.confij.props.PropertiesConfiguration;

/**
 * 
 * @author daniel
 * 
 */
public class DirBasedConfigLoader extends AppConfigLoader {
	private static final Logger logger = LoggerFactory.getLogger(DirBasedConfigLoader.class);
	
	private File configDir;

	public DirBasedConfigLoader(File configDir, String appName) {
		super(appName);
		this.configDir = configDir;
		assertConfigDirExists(appName);
	}

	public File getConfigDir() {
		return configDir;
	}

	public Configuration getConfiguration(String configFileName) throws ConfigException {
		return getConfiguration(configFileName, null);
	}

	public Configuration getConfiguration(String configFileName, String charset)
			throws ConfigException {
		File confFile = getConfigFile(appName, configFileName, true);
		if (configFileName.endsWith(".properties")) {
			return charset == null ? new PropertiesConfiguration(confFile)
					: new PropertiesConfiguration(confFile, charset);
		} else if (confFile.getName().endsWith(".ini")) {
			return new IniConfiguration(confFile);
		}
		throw new UnsupportedOperationException();
	}

	public File getConfigFile(String configFileName) {
		return getConfigFile(appName, configFileName, false);
	}

	public File getConfigFile(String appName, String configFileName, boolean create) {
		// first look on current dir

		File configFile = new File(configFileName);

		if (!configFile.exists()) {
			// File configFilesDir = getConfigFilesDir(appName);
			if (create) {
				return assertConfiguration(configFileName);
			}
			return null;
		}

		// if(SystemUtils.IS_OS_LINUX){
		//
		// }
		// else if(SystemUtils.IS_OS_WINDOWS){
		// }

		return configFile;
	}

	public File assertConfiguration(String configFileName) {
		File configFile = new File(configDir, configFileName);
		if (!configFile.exists()) {
			try {
				configFile.createNewFile();
				logger.info("Created file " + configFile);
				return configFile;
			} catch (IOException e) {
				e.printStackTrace();
				return null;
			}
		}
		return configFile;
	}

	private void assertConfigDirExists(String appName) {
		if (!configDir.exists()) {
			try {
				FileUtils.forceMkdir(configDir);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
